#include <QtWidgets>

#include "CNwidget.h"
#include "coreutil/touch.c.h"
#include "coreutil/ln.c.h"

QLabel *CNWidget::createDragLabel(const QString &text, QWidget *parent)
{

    QLabel *label = new QLabel(text, parent);
    label->setAutoFillBackground(true);
    label->setBackgroundRole(QPalette::Midlight);
    label->setForegroundRole(QPalette::WindowText);
    label->setFrameShape(QFrame::Panel);
    label->setFrameShadow(QFrame::Raised);
    mlist.append(label);
    return label;
}
void CNWidget::SelectDragLabel(int inum)
{
   int isize = mlist.size();
   if(inum<isize)
   {
       for(int i=0;i<isize;i++)
       {
           mlist[i]->setBackgroundRole(QPalette::Background);
           mlist[i]->setForegroundRole(QPalette::Foreground);
       }
       mlist[inum]->setBackgroundRole(QPalette::Highlight);
       mlist[inum]->setForegroundRole(QPalette::HighlightedText);

   }
}
void CNWidget::deleteDragLabel()
{
    int isize = mlist.size();
    for(int it=0;it<isize;it++)
    {
        delete mlist.at(it);
    }
    mlist.clear();
}

static QString hotSpotMimeDataKey() { return QStringLiteral("application/x-hotspot"); }
CNWidget::CNWidget(QWidget *parent)
    : QWidget(parent)
{
    QFont font("Times", 12);
    font.setStyleStrategy(QFont::ForceOutline);
    mbefore  = QString("");
    mibegin = 0;
    miend =0;
    mireplacebegin = 0;
    mireplaceend = 0;
    mselecteditcn = 0;
    mpinyinnum = 0;
    mcinum = 0;
    miwith = 785;
    micurselkey= 0;
    medit = new QTextEdit(this);
    medit->setMaximumHeight(23);
    medit->setMinimumWidth(630);
    medit->setMaximumWidth(1200);
    medit->setFont(font);
    medit->move(0, 0);
    medit->show();
    connect(medit, &QTextEdit::textChanged,
        this, &CNWidget::EditTextChanged);

    mshowci = 0;
    mshowpinyin = 0;


    PinYinZhiDir(QString("usemore"));
   mpinyinnum = ShowPinYin(0,1);
 //  setWindowFlag(Qt::FramelessWindowHint);
}

QString CNWidget::getstring()
{
    return medit->toPlainText();
}
void CNWidget::EditTextChanged()
{
    QString strtext =  medit->toPlainText();
    if(0 == strtext.size())
    {
        if(mselecteditcn ==0)
        {
            mbefore.clear();
            mibegin =0;
            miend =0;

            micurselkey= 0;
        }
        mselecteditcn =0;
        return;
    }
    if(strtext.mid(strtext.size()-1)==QString("\n"))
    {
        int isize = mbefore.size();
        mibegin =isize;
        miend =strtext.size();
        QString strtextafter =  strtext.mid(isize,miend-mibegin-1);


        if(strtextafter.size()>0)
        {
           // PinYinZhiDir(strtextafter);
            if(mfiles.size()>0)
            {
                mbefore = mbefore +  mfiles[0];

                medit->setText(mbefore);
                QTextCursor tc = medit->textCursor();
                tc.movePosition(QTextCursor::EndOfWord);
               // tc.movePosition(QTextCursor::End);
                medit->setTextCursor(tc);

            }
        }


        PinYinZhiDir(QString("usemore"));
         mpinyinnum = ShowPinYin(0,1);
        mshowci = 0;
         return;
    }


   int isize = mbefore.size();
   mibegin =isize;
   miend =strtext.size();
   QString strtextafter =  strtext.mid(isize);


   PinYinZhiDir(strtextafter);
    mpinyinnum = ShowPinYin(0,1);
     //   mpagenum =0;
    mshowci = 0;
    micurselkey= 0;
}
void CNWidget::PinYinZhiDir(const QString &str)
{
    mfiles.clear();
    mfiledirs.clear();
    if(str.length()>1)
    { //getlocationstring(
        QString path = QString("/data/PinYin/")+str.at(0)+QString("/");

        const QDir dir(path);
        foreach (const QFileInfo &adirname, dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot))
        {
            const QString secdirname = path + adirname.fileName();

            if(adirname.baseName().mid(0,str.size())==str
                    ||adirname.baseName()==str)
            {
                QDir secdir(secdirname);
                secdir.setSorting(QDir::Time);

                foreach (const QFileInfo &adirznname,secdir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot ))
                {
                    mfiles << adirznname.baseName();
                    mfiledirs << secdirname + "/" + adirznname.baseName();
                }
            }
        }
   }
}

void CNWidget::PinYinCiDir(const QString &dirstr)
{

    mfileCis.clear();
    mfileCisdirs.clear();
    //if(str.length()>1)
    { //getlocationstring(
        QString path = dirstr;//QString("/media/cxy/Q/linux/PinYin/")+str.at(0)+QString("/");

        const QDir dir(path);

        foreach (const QFileInfo &adirname, dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot))
        {
           mfileCis << adirname.fileName();
           mfileCisdirs << path + "/" + adirname.baseName();
        }
     }
}


int CNWidget::ShowCi(int ipage,int iaddormud)
{
    int ifilesize = mfileCis.size();
    if(ipage<0)
        ipage = 0;

    int x = 0;
    int y = 23;
    QFont font("Times", 12);
    font.setStyleStrategy(QFont::ForceOutline);

        {

        int istringlen = 0;
        int irunsize = 0;
        int ibegin = ipage;
        int iend = irunsize;
        if(iaddormud<0)
        {
            irunsize = 0;///here
            int irb = ipage<0?0:ipage;
            irb = (ipage>=ifilesize?ifilesize-1:ipage);
            istringlen = 0;
            for(int ir = irb;ir>=0;ir--)
            {
                if(istringlen<=20)
                     istringlen =istringlen + mfileCis.at(ir).size();
                else
                {
                       irunsize = ir;
                    break;
                }
             }
            ibegin = irb;
            iend = irunsize <0?0:irunsize;
            irunsize = 0;
            istringlen = 0;
            if(iend>0)
            {
                for(int ir = iend;ir>=0;ir--)
                {
                    if(istringlen<=20)
                         istringlen =istringlen + mfileCis.at(ir).size();
                    else
                    {
                        irunsize = ir;
                        break;
                    }
                 }

                ibegin =  irunsize;

                iend = iend;
            }
            ipage = ibegin;

        }
//if(iaddormud>0)
{
    irunsize = ifilesize;
istringlen =0;
    for(int ir = ipage;ir<ifilesize;ir++)
    {
        if(istringlen<=20)
             istringlen =istringlen + mfileCis.at(ir).size();
        else
        {
            irunsize = ir;
            break;
        }
     }
    ibegin = ipage;

    iend = irunsize;
}

        if(ibegin<ifilesize)
            {
                 deleteDragLabel();
                for(int i=ibegin;i<iend;i++)//ifilesize
                {
                    QLabel *wordLabel = createDragLabel(mfileCis.at(i), this);

                    wordLabel->move(x, y);
                    wordLabel->setFont(font);
                    wordLabel->show();
                    wordLabel->setAttribute(Qt::WA_DeleteOnClose);
                    x += wordLabel->width() + 2;
                    if (x >= miwith)
                    {
                        x = 5;
                        y += wordLabel->height() + 2;
                    }
                }
               /* for(int i=iend;i<ibegin+20;i++)//ifilesize
                {
                    QLabel *wordLabel = createDragLabel("   ", this);
                    wordLabel->move(x, y);
                    wordLabel->setFont(font);
                    wordLabel->show();
                    wordLabel->setAttribute(Qt::WA_DeleteOnClose);
                    x += wordLabel->width() + 2;
                    if (x >= miwith)
                    {
                        x = 5;
                        y += wordLabel->height() + 2;
                    }
                } */
                {
                    QLabel *wordLabel = createDragLabel("<", this);
                    wordLabel->move(x, y);
                    wordLabel->setFont(font);
                    wordLabel->show();
                    wordLabel->setAttribute(Qt::WA_DeleteOnClose);
                    x += wordLabel->width() + 2;
                    if (x >= miwith)
                    {
                        x = 5;
                        y += wordLabel->height() + 2;
                    }
                 }
                {
                    QLabel *wordLabel = createDragLabel(">", this);
                    wordLabel->move(x, y);
                    wordLabel->setFont(font);
                    wordLabel->show();
                    wordLabel->setAttribute(Qt::WA_DeleteOnClose);
                    x += wordLabel->width() + 2;
                    if (x >= miwith)
                    {
                        x = 5;
                        y += wordLabel->height() + 2;
                    }
                 }

                for(int j=0;j<4;j++)
                {
                    QLabel *wordLabel = createDragLabel("   ", this);
                    wordLabel->move(x, y);
                    wordLabel->setFont(font);
                    wordLabel->show();
                    wordLabel->setAttribute(Qt::WA_DeleteOnClose);
                    x += wordLabel->width() + 2;
                    if (x >= miwith)
                    {
                        x = 5;
                        y += wordLabel->height() + 2;
                    }
                }
            }

        return iend >ifilesize?ifilesize:iend;
        }
}

int CNWidget::ShowPinYin(int ipage,int iaddormud)
{
    int ifilesize = mfiles.size();
    if(ipage<0)
        ipage = 0;

    int x = 0;
    int y = 23;
    QFont font("Times", 12);
    font.setStyleStrategy(QFont::ForceOutline);

        {

        int istringlen = 0;
        int irunsize = 0;
        int ibegin = ipage;
        int iend = irunsize;
if(iaddormud<0)
        {
            irunsize = 0;///here

            int irb = ipage<0?0:ipage;
            irb = (ipage>=ifilesize?ifilesize-1:ipage);
            istringlen = 0;
            for(int ir = irb;ir>=0;ir--)
            {
                if(istringlen<=20)
                     istringlen =istringlen + mfiles.at(ir).size();
                else
                {
                       irunsize = ir;
                    break;
                }
             }
            ibegin = irb;
            iend = irunsize <0?0:irunsize;
            irunsize = 0;
            istringlen = 0;
            if(iend>0)
            {
                for(int ir = iend;ir>=0;ir--)
                {
                    if(istringlen<=20)
                         istringlen =istringlen + mfiles.at(ir).size();
                    else
                    {
                        irunsize = ir;
                        break;
                    }
                 }

                ibegin =  irunsize;

                iend = iend;
            }
            ipage = ibegin;

        }
//if(iaddormud>0)
{
    irunsize = ifilesize;
istringlen =0;
    for(int ir = ipage;ir<ifilesize;ir++)
    {
        if(istringlen<=20)
             istringlen =istringlen + mfiles.at(ir).size();
        else
        {
            irunsize = ir;
            break;
        }
     }
    ibegin = ipage;

    iend = irunsize;
}

        if(ibegin<ifilesize)
            {
                 deleteDragLabel();
                for(int i=ibegin;i<iend;i++)//ifilesize
                {
                    QLabel *wordLabel = createDragLabel(mfiles.at(i), this);

                    wordLabel->move(x, y);
                    wordLabel->setFont(font);
                    wordLabel->show();
                    wordLabel->setAttribute(Qt::WA_DeleteOnClose);
                    x += wordLabel->width() + 2;
                    if (x >= miwith)
                    {
                        x = 5;
                        y += wordLabel->height() + 2;
                    }
                }
               /* for(int i=iend;i<ibegin+20;i++)//ifilesize
                {
                    QLabel *wordLabel = createDragLabel("   ", this);
                    wordLabel->move(x, y);
                    wordLabel->setFont(font);
                    wordLabel->show();
                    wordLabel->setAttribute(Qt::WA_DeleteOnClose);
                    x += wordLabel->width() + 2;
                    if (x >= miwith)
                    {
                        x = 5;
                        y += wordLabel->height() + 2;
                    }
                } */
                {
                    QLabel *wordLabel = createDragLabel("<", this);
                    wordLabel->move(x, y);
                    wordLabel->setFont(font);
                    wordLabel->show();
                    wordLabel->setAttribute(Qt::WA_DeleteOnClose);
                    x += wordLabel->width() + 2;
                    if (x >= miwith)
                    {
                        x = 5;
                        y += wordLabel->height() + 2;
                    }
                 }
                {
                    QLabel *wordLabel = createDragLabel(">", this);
                    wordLabel->move(x, y);
                    wordLabel->setFont(font);
                    wordLabel->show();
                    wordLabel->setAttribute(Qt::WA_DeleteOnClose);
                    x += wordLabel->width() + 2;
                    if (x >= miwith)
                    {
                        x = 5;
                        y += wordLabel->height() + 2;
                    }
                 }

                for(int j=0;j<4;j++)
                {
                    QLabel *wordLabel = createDragLabel("   ", this);
                    wordLabel->move(x, y);
                    wordLabel->setFont(font);
                    wordLabel->show();
                    wordLabel->setAttribute(Qt::WA_DeleteOnClose);
                    x += wordLabel->width() + 2;
                    if (x >= miwith)
                    {
                        x = 5;
                        y += wordLabel->height() + 2;
                    }
                }
            }

        return iend >ifilesize?ifilesize:iend;
        }
}
void CNWidget::touch(QString qstrfile)
{

    int argc = 2;
    char **argv=new char*[2];
    argv[0] = "touch";
    argv[1] = (char*)qstrfile.toLocal8Bit().constData();

    maintouch(argc, argv);

}
void CNWidget::ln(QString qstrfilesrc,QString qstrfiledes)
{

    int argc = 2;
    char **argv=new char*[2];
    argv[0] = (char*)qstrfilesrc.toLocal8Bit().constData();
    argv[1] = (char*)qstrfiledes.toLocal8Bit().constData();

    mainln(argc, argv);

}

void CNWidget::dragEnterEvent(QDragEnterEvent *event)
{
    if (event->mimeData()->hasText()) {
        if (event->source() == this) {
            event->setDropAction(Qt::MoveAction);
            event->accept();
        } else {
            event->acceptProposedAction();
        }
    } else {
        event->ignore();
    }
}

void CNWidget::dropEvent(QDropEvent *event)
{
    if (event->mimeData()->hasText()) {
        const QMimeData *mime = event->mimeData();
        QStringList pieces = mime->text().split(QRegularExpression(QStringLiteral("\\s+")),
                             QString::SkipEmptyParts);
        QPoint position = event->pos();
        QPoint hotSpot;

        QByteArrayList hotSpotPos = mime->data(hotSpotMimeDataKey()).split(' ');
        if (hotSpotPos.size() == 2) {
            hotSpot.setX(hotSpotPos.first().toInt());
            hotSpot.setY(hotSpotPos.last().toInt());
        }

        for (const QString &piece : pieces) {
            QLabel *newLabel = createDragLabel(piece, this);
            newLabel->move(position - hotSpot);
            newLabel->show();
            newLabel->setAttribute(Qt::WA_DeleteOnClose);

            position += QPoint(newLabel->width(), 0);
        }

        if (event->source() == this) {
            event->setDropAction(Qt::MoveAction);
            event->accept();
        } else {
            event->acceptProposedAction();
        }
    } else {
        event->ignore();
    }
    for (QWidget *widget : findChildren<QWidget *>()) {
        if (!widget->isVisible())
            widget->deleteLater();
    }
}

void CNWidget::mousePressEvent(QMouseEvent *event)
{
    QLabel *child = qobject_cast<QLabel*>(childAt(event->pos()));
    if (!child)
        return;
/*
    QPoint hotSpot = event->pos() - child->pos();

    QMimeData *mimeData = new QMimeData;

    mimeData->setText(child->text());
    mimeData->setData(hotSpotMimeDataKey(),
                      QByteArray::number(hotSpot.x()) + ' ' + QByteArray::number(hotSpot.y()));

    qreal dpr = window()->windowHandle()->devicePixelRatio();
    QPixmap pixmap(child->size() * dpr);
    pixmap.setDevicePixelRatio(dpr);
    child->render(&pixmap);

    QDrag *drag = new QDrag(this);
    drag->setMimeData(mimeData);
    drag->setPixmap(pixmap);
    drag->setHotSpot(hotSpot);

    Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction);

    if (dropAction == Qt::MoveAction)
        child->close();
*/
    QString strtext = child->text();
    if(strtext==QString("   "))
    {

        PinYinZhiDir(QString("usemore"));
        mpinyinnum = ShowPinYin(0,1);
      //  mpagenum = 0;
        mshowci = 0;
        mshowpinyin = 0;
    }
    else if(strtext==QString(">"))
    {
        if(0==mshowci)
        {
           // mpagenum =mpagenum+1;
           mpinyinnum = ShowPinYin(mpinyinnum,1);
        }
        else
        {

            //mcinum =mcinum+1;
            mcinum = ShowCi(mcinum,1);
        }
    }
    else if(strtext==QString("<"))
    {
        if(0==mshowci)
        {
           // mpagenum =mpagenum-1;
            mpinyinnum = ShowPinYin(mpinyinnum,-1);
        }
        else
        {
            //mcinum =mcinum - 1;
            mcinum = ShowCi(mcinum,-1);
        }
    }
    else
    {
        if(0==mshowci)
        {
            QString strget;
            int ifsize = mfiles.size();
            for(int i=0;i<ifsize;i++)
            {
               if(strtext == mfiles[i])
               {
                   strget = mfiledirs[i];
               }
            }
            mselecteditcn = 1;
            medit->setText(QString(""));
            medit->insertPlainText(mbefore+strtext);

            QString qstrdes = QString("/data/PinYin/u/usemore/") + strtext;
            if(strget!=qstrdes)
            ln(strget,qstrdes);
            touch(strget);

             mbefore = mbefore+strtext;

             PinYinCiDir(strget);
             ShowCi(0,1);

             mshowci = 1;
        }
        else
        {
            QString strget;
            int ifsize = mfileCis.size();

            for(int i=0;i<ifsize;i++)
            {
               if(strtext == mfileCis[i])
               {
                   strget = mfileCisdirs[i];
               }
            }

            mselecteditcn = 1;
            medit->setText(QString(""));
            medit->insertPlainText(mbefore.mid(0,mbefore.size()-1)+strtext);

            QString qstrdes = QString("/data/PinYin/u/usemore/") + strtext;
             if(strget!=qstrdes)
            ln(strget,qstrdes);
             touch(strget);


            /*   if(ifilesize<20)
               {
                   for(int i=0;i<ifilesize;i++)//ifilesize
                   {
                       QLabel *wordLabel = createDragLabel(mfiles.at(i), this);
                       wordLabel->move(x, y);
                       wordLabel->show();
                       wordLabel->setAttribute(Qt::WA_DeleteOnClose);
                       x += wordLabel->width() + 2;
                       if (x >= miwith)
                       {
                           x = 5;
                           y += wordLabel->height() + 2;
                       }
                   }

                   for(int i=ifilesize;i<22;i++)//ifilesize
                   {
                       QLabel *wordLabel = createDragLabel("   ", this);
                       wordLabel->move(x, y);
                       wordLabel->show();
                       wordLabel->setAttribute(Qt::WA_DeleteOnClose);
                       x += wordLabel->width() + 2;
                       if (x >= miwith)
                       {
                           x = 5;
                           y += wordLabel->height() + 2;
                       }
                   }
                   {
                       QLabel *wordLabel = createDragLabel(">>", this);
                       wordLabel->move(x, y);
                       wordLabel->show();
                       wordLabel->setAttribute(Qt::WA_DeleteOnClose);
                       x += wordLabel->width() + 2;
                       if (x >= miwith)
                       {
                           x = 5;
                           y += wordLabel->height() + 2;
                       }
                    }
               }
               else
                   */
             mbefore = mbefore.mid(0,mbefore.size()-1)+strtext;

             PinYinZhiDir(QString("usemore"));
              mpinyinnum = ShowPinYin(0,1);
             mshowci = 0;
        }

     }


}

void CNWidget::keyPressEvent(QKeyEvent *event)
{
     //deleteDragLabel();
     //PinYinZhiDir(QString("ci"));

    switch (event->key())
    {
        case  Qt::Key_Down:
            break;
        case  Qt::Key_Up:
            break;
        case  Qt::Key_Left:
                if(micurselkey<mlist.size()-1)
                {
                    micurselkey = micurselkey + 1;
                    SelectDragLabel(micurselkey);
                }
            break;
        case  Qt::Key_Right:
                if(micurselkey>0)
                {
                    micurselkey = micurselkey - 1;
                    SelectDragLabel(micurselkey);
                }
            break;
        case  Qt::Key_Enter:
            break;
        case  Qt::Key_Return:
            break;
        case  Qt::Key_Space:
            break;
        default:
            break;
    }
#ifndef QT_NO_SHORTCUT
    if ((windowType() == Qt::Popup) && event->matches(QKeySequence::Cancel))
    {
        event->accept();
        close();
    }
    else
#endif
    {
        event->ignore();
    }
}
